<template>
  <div class="permission-management animate-in">
    <div class="permission-card">
      <el-row justify="start" align="middle" style="margin-bottom: 16px; gap: 12px;">
        <el-col style="flex: none;">
          <el-select v-model="statusFilter" placeholder="筛选状态" clearable style="width: 120px; margin-right: 8px;">
            <el-option label="全部" :value="''" />
            <el-option label="启用" :value="'enabled'" />
            <el-option label="禁用" :value="'disabled'" />
          </el-select>
        </el-col>
        <el-col style="flex: none;">
          <el-input v-model="filterText" placeholder="搜索权限名或编码" clearable style="width: 200px;" />
        </el-col>
        <el-col style="flex: none;">
          <el-button class="create-permission-btn" @click="openCreateDialog">新建权限</el-button>
        </el-col>
      </el-row>
      <el-table :data="pagedTableData" row-key="Id" style="width: 100%" v-loading="loading" class="pretty-table">
        <el-table-column prop="PermissionName" label="权限名" align="left" />
        <el-table-column prop="Code" label="权限编码" align="left" />
        <el-table-column prop="IsActived" label="启用状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.IsActived ? 'success' : 'info'">
              {{ scope.row.IsActived ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div class="permission-actions-row">
              <el-button size="small" @click="openEditDialog(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                size="small"
                :type="scope.row.IsActived ? 'danger' : 'success'"
                @click="togglePermissionStatus(scope.row)"
              >
                <el-icon><SwitchButton /></el-icon>
                {{ scope.row.IsActived ? '禁用' : '启用' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          :page-size="pageSize"
          :current-page="currentPage"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新建/编辑权限对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="权限名" prop="PermissionName">
          <el-input v-model="form.PermissionName" placeholder="请输入权限名" />
        </el-form-item>
        <el-form-item label="权限编码" prop="Code">
          <el-input v-model="form.Code" placeholder="请输入权限编码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" :disabled="formLoading">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="formLoading">
          {{ formLoading ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, SwitchButton } from '@element-plus/icons-vue'
import { getPermissionList, createPermission, updatePermission, deletePermission, togglePermissionStatus as togglePermissionStatusApi } from '@/api/permission'

const permissions = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const formLoading = ref(false)
const dialogTitle = ref('')
const form = reactive({ Id: '', PermissionName: '', Code: '' })
const formRules = {
  PermissionName: [{ required: true, message: '请输入权限名', trigger: 'blur' }],
  Code: [{ required: true, message: '请输入权限编码', trigger: 'blur' }]
}
const formRef = ref()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

const statusFilter = ref('')
const filterText = ref('')

const tableData = computed(() => Array.isArray(permissions.value) ? permissions.value.slice() : [])

const filteredTableData = computed(() => {
  let data = tableData.value
  if (statusFilter.value === 'enabled') {
    data = data.filter(item => item.IsActived)
  } else if (statusFilter.value === 'disabled') {
    data = data.filter(item => !item.IsActived)
  }
  if (filterText.value) {
    const keyword = filterText.value.trim().toLowerCase()
    data = data.filter(item =>
      (item.PermissionName && item.PermissionName.toLowerCase().includes(keyword)) ||
      (item.Code && item.Code.toLowerCase().includes(keyword))
    )
  }
  return data
})

// 分页后的数据
const pagedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTableData.value.slice(start, end)
})

// 添加缓存机制
const permissionCache = ref(new Map())

// 优化的权限数据获取函数
async function fetchPermissions() {
  loading.value = true
  
  try {
    const res = await getPermissionList()
    
    if (res?.Data) {
      permissions.value = res.Data
      // 更新缓存
      res.Data.forEach(perm => permissionCache.value.set(perm.Id, perm))
    } else {
      permissions.value = []
      ElMessage.warning('未获取到权限列表')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    permissions.value = []
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

function openCreateDialog() {
  dialogTitle.value = '新建权限'
  form.Id = ''
  form.PermissionName = ''
  form.Code = ''
  dialogVisible.value = true
}

function openEditDialog(row) {
  dialogTitle.value = '编辑权限'
  form.Id = row.Id
  form.PermissionName = row.PermissionName
  form.Code = row.Code
  dialogVisible.value = true
}

// 优化的权限保存函数
async function handleSave() {
  const valid = await formRef.value.validate()
  if (!valid) return
  
  formLoading.value = true
  
  try {
    if (form.Id) {
      // 编辑权限
      await updatePermission(form.Id, {
        PermissionName: form.PermissionName,
        Code: form.Code
      })
      ElMessage.success('权限更新成功')
    } else {
      // 新建权限
      await createPermission({
        PermissionName: form.PermissionName,
        Code: form.Code
      })
      ElMessage.success('权限创建成功')
    }
    
    dialogVisible.value = false
    
    // 清除缓存，强制重新获取数据
    permissionCache.value.clear()
    await fetchPermissions()
    
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存失败')
  } finally {
    formLoading.value = false
  }
}

// 优化的权限状态切换函数
async function togglePermissionStatus(row) {
  try {
    const res = await togglePermissionStatusApi(row.Id, row.IsActived)
    
    if (res?.Code === 200) {
      ElMessage.success(res.Message || (row.IsActived ? '禁用成功' : '启用成功'))
      // 只更新当前权限的状态，避免重新获取所有数据
      row.IsActived = !row.IsActived
    } else if (res?.Message) {
      ElMessage.error(res.Message)
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('切换权限状态失败:', error)
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message)
    } else {
      ElMessage.error('操作失败')
    }
  }
}

function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}
function handleCurrentChange(val) {
  currentPage.value = val
}

onMounted(() => {
  fetchPermissions()
})
</script>
<style scoped>
.permission-management {
  background: #f5f7fa;
  min-height: calc(100vh - 52px);
  padding: 0 0 60px 0;
}
.permission-card {
  background: transparent;
  border-radius: 18px;
  box-shadow: none;
  padding: 8px 24px 24px 24px;
  max-width: 100%;
  margin: 0 auto;
  height: calc(100vh - 172px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.pretty-table {
  background: transparent !important;
  border-radius: 14px;
  font-size: 16px;
  width: 100%;
  flex: 1;
  overflow: hidden;
}
.pretty-table th {
  background: #f5f7fa !important;
  color: #3a4664;
  font-weight: 700;
  border-bottom: 1.5px solid #e6e8eb !important;
  letter-spacing: 0.5px;
  font-size: 15px;
  padding: 14px 12px !important;
  text-align: left !important;
}
.pretty-table td {
  background: #fff !important;
  border-bottom: 1.5px solid #f0f0f0 !important;
  color: #2d3a4a;
  font-size: 15px;
  text-align: left !important;
}
.pretty-table .el-table__row:hover > td {
  background: #f0f6ff !important;
}
.create-permission-btn {
  background: #409eff !important;
  color: #ffffff !important;
  border: none !important;
  border-radius: 4px !important;
  font-weight: 500;
  font-size: 14px;
  padding: 8px 16px !important;
  box-shadow: none;
  transition: all 0.2s;
  margin-bottom: 0;
}
.create-permission-btn:hover {
  background: #337ecc !important;
  color: #ffffff !important;
}
.permission-actions-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
  justify-content: center;
  height: 100%;
}
.permission-actions-row .el-button {
  min-width: 72px;
  width: 72px;
  height: 32px;
  font-size: 14px;
  padding: 0 12px;
  border-radius: 4px;
  margin-right: 0;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}
.permission-actions-row .el-button:last-child {
  margin-right: 0;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
}
</style>
